package cn.iocoder.yudao.module.promotion.gift.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.annotation.AdminJsonView;
import cn.iocoder.yudao.framework.business.basic.controller.CrudController;
import cn.iocoder.yudao.framework.business.basic.controller.SimpleDetailController;
import cn.iocoder.yudao.framework.business.basic.pojo.vo.ShopSimpleVO;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils;
import cn.iocoder.yudao.module.api.promotion.gift.dto.GiftActivityVO;
import cn.iocoder.yudao.module.api.shop.info.ShopInfoApi;
import cn.iocoder.yudao.module.promotion.gift.pojo.dto.GiftScanConfigQueryDTO;
import cn.iocoder.yudao.module.promotion.gift.pojo.dto.GiftScanConfigSaveDTO;
import cn.iocoder.yudao.module.promotion.gift.pojo.vo.GiftScanConfigVO;
import cn.iocoder.yudao.module.promotion.gift.service.admin.GiftActivityService;
import cn.iocoder.yudao.module.promotion.gift.service.admin.GiftScanConfigService;
import com.fasterxml.jackson.annotation.JsonView;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.isSuperAdmin;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * 前端控制器
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/05/27
 */
@Tag(name = "管理后台 - 扫送配置")
@RestController
@RequestMapping("/promotion/gift/scan/config")
public class GiftScanConfigController implements SimpleDetailController<GiftScanConfigVO>, CrudController<GiftScanConfigVO, GiftScanConfigSaveDTO, GiftScanConfigQueryDTO> {
    @Resource
    private GiftScanConfigService giftScanConfigService;
    @Resource
    private GiftActivityService giftActivityService;

    @Resource
    private ShopInfoApi shopInfoApi;

    @PreAuthorize("@ss.hasAnyRoles('super_admin', 'platform_admin', 'tenant_admin', 'shop_admin')")
    @JsonView(AdminJsonView.class)
    @Override
    public CommonResult<GiftScanConfigVO> getDetail(Long id) {
        GiftScanConfigVO data;
        if (isSuperAdmin()) {
            data = DataPermissionUtils.executeIgnore(() -> giftScanConfigService.getDetail(id));
        } else {
            data = giftScanConfigService.getDetail(id);
        }
        // 获取别的商家的赠品活动，需要忽略店铺数据权限
        List<GiftActivityVO> list = DataPermissionUtils.executeIgnore(() -> giftActivityService.getList(data.getGiftActivityIds()));
        if (CollUtil.isNotEmpty(list)) {
            data.setGiftActivityNames(list.stream()
                    .map(GiftActivityVO::getName)
                    .filter(Objects::nonNull)
                    .toList());
        }
        return CommonResult.success(data);
    }

    @PreAuthorize("@ss.hasAnyRoles('super_admin', 'platform_admin', 'tenant_admin', 'shop_admin')")
    @JsonView(AdminJsonView.class)
    @Override
    public CommonResult<PageResult<GiftScanConfigVO>> getPage(Integer pageNo, Integer pageSize, GiftScanConfigQueryDTO param) {
        PageResult<GiftScanConfigVO> data;
        if (isSuperAdmin()) {
            data = DataPermissionUtils.executeIgnore(() -> giftScanConfigService.getPage(pageNo, pageSize, param));
        } else {
            data = giftScanConfigService.getPage(pageNo, pageSize, param);
        }
        if (CollUtil.isEmpty(data.getList())) {
            return CommonResult.success(PageResult.empty());
        }
        Set<Long> shopIds = data.getList().stream()
                .map(GiftScanConfigVO::getShopId)
                .collect(Collectors.toSet());
        Map<Long, ShopSimpleVO> shopIdToShopMap = shopInfoApi.getShopSimpleMap(shopIds);
        Set<Long> giftActivityIds = data.getList().stream()
                .map(GiftScanConfigVO::getGiftActivityIds)
                .flatMap(List::stream)
                .collect(Collectors.toSet());
        // 获取别的商家的赠品活动，需要忽略店铺数据权限
        List<GiftActivityVO> list = DataPermissionUtils.executeIgnore(() -> giftActivityService.getList(giftActivityIds));
        Map<Long, String> idToNameMap = new HashMap<>();
        if (CollUtil.isNotEmpty(list)) {
            idToNameMap = list.stream().collect(Collectors.toMap(GiftActivityVO::getId, GiftActivityVO::getName));
        }
        for (GiftScanConfigVO item : data.getList()) {
            item.setShop(shopIdToShopMap.getOrDefault(item.getShopId(), ShopSimpleVO.EMPTY));
            List<String> names = item.getGiftActivityIds().stream()
                    .map(idToNameMap::get)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            item.setGiftActivityNames(names);
        }
        return CommonResult.success(data);
    }

    @PreAuthorize("@ss.hasRole('shop_admin')")
    @Override
    public CommonResult<Long> create(GiftScanConfigSaveDTO param) {
        // TODO 重复性判断
        return CommonResult.success(giftScanConfigService.create(param));
    }

    @PreAuthorize("@ss.hasAnyRoles('super_admin', 'platform_admin', 'tenant_admin', 'shop_admin')")
    @Override
    public CommonResult<Boolean> update(GiftScanConfigSaveDTO param) {
        // TODO 重复性判断
        if (isSuperAdmin()) {
            return CommonResult.success(DataPermissionUtils.executeIgnore(() -> giftScanConfigService.update(param)));
        }
        return CommonResult.success(giftScanConfigService.update(param));
    }

    @PreAuthorize("@ss.hasRole('shop_admin')")
    @Override
    public CommonResult<Boolean> delete(Long id) {
        return CommonResult.success(giftScanConfigService.delete(id));
    }

}
